<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ page import="java.io.*,java.util.*, javax.servlet.*"%>
<%@ page import="javax.servlet.http.*"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="org.apache.commons.fileupload.disk.*"%>
<%@ page import="org.apache.commons.fileupload.servlet.*"%>
<%@ page import="org.apache.commons.io.output.*"%>
<%
	// Variables.
	String scholarship_id = "1";
	String user = (String) session.getAttribute("user");

	//Store the location to write the file and the submitted file. /////////////////////////////////////////////////////////////////////
	File file = null;
	FileItem input = null;

	int maxFileSize = 5000 * 1024;
	int maxMemSize = 5000 * 1024;
	ServletContext context = pageContext.getServletContext();
	String filePath = application.getRealPath("application_documents") + "\\";

	// Verify the content type
	String contentType = request.getContentType();
	if ((contentType.indexOf("multipart/form-data") >= 0)) {

		DiskFileItemFactory factory = new DiskFileItemFactory();
		// maximum size that will be stored in memory
		factory.setSizeThreshold(maxMemSize);
		// Location to save data that is larger than maxMemSize.
		factory.setRepository(new File(filePath));

		// Create a new file upload handler
		ServletFileUpload upload = new ServletFileUpload(factory);
		// maximum file size to be uploaded.
		upload.setSizeMax(maxFileSize);
		try {
			// Parse the request to get file items.
			@SuppressWarnings("unchecked")
			List<FileItem> fileItems = upload.parseRequest(request);

			// Process the uploaded file items
			Iterator<FileItem> i = fileItems.iterator();

			while (i.hasNext()) {
				FileItem fi = (FileItem) i.next();
				if (!fi.isFormField()) {
					// Get the uploaded file parameters
					String fieldName = fi.getFieldName();
					String fileName = fi.getName();
					boolean isInMemory = fi.isInMemory();
					long sizeInBytes = fi.getSize();
					// Write the file
					if (fileName.lastIndexOf("\\") >= 0) {
						file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
					} else {
						file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
					}
					//fi.write(file);
					input = fi; // Store the submitted file. Do not write until the text components have been validated.
				} else {
					// FileItem is a form field.
					String value = fi.getString();
					if (fi.getFieldName().equalsIgnoreCase("scholarship_id")) {
						scholarship_id = value;
					}
				}
			}

			// Getting information and updating the database.
			java.sql.Connection conn = null;
			String myJDBCDriver = (String) session.getAttribute("myJDBCDriver");
			String myURL = (String) session.getAttribute("myURL");
			String myUserID = (String) session.getAttribute("myUserID");
			String myPassword = (String) session.getAttribute("myPassword");

			// Connect to the database.
			Class.forName(myJDBCDriver).newInstance();
			java.util.Properties sysprops = System.getProperties();
			sysprops.put("user", myUserID);
			sysprops.put("password", myPassword);
			conn = java.sql.DriverManager.getConnection(myURL, sysprops);

			java.sql.Statement statement = conn.createStatement();
			String query = "INSERT INTO applications (applicant, scholarship_id, finished, date_submitted) VALUES ('" + user + "','"
					+ scholarship_id + "','1', NOW())";
			statement.executeUpdate(query);

			// Try to write the file.
			java.sql.ResultSet rs = statement.executeQuery("SELECT LAST_INSERT_ID()");
			rs.next();
			try {
				String extension = file.getName().substring(file.getName().lastIndexOf('.'), file.getName().length());
				file = new File(file.getParent() + "\\" + rs.getString(1) + extension);
				input.write(file);
			} catch (Exception e) { // No file was uploaded.
			}
			
			session.setAttribute("errors", "Application Successfully Submitted! If you need to update your information, edit your profile.");
			session.setAttribute("scholarship_id", scholarship_id);
			response.sendRedirect("apply.jsp");
		} catch (Exception ex) {
			out.println(ex);
			ex.printStackTrace();
		}
	}
%>